<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        window.onload = function(){
            var box = document.getElementsByClassName("box")[0];
            // 设置速度
            var speed = 8;
            // 设置移动方向
            var kc = 0;


            // 用按键来单独控制移动速度(从而使物体运动时不会卡顿)
            document.onkeydown = function(event){
                // 按下ctrl加速
                if (event.ctrlKey){
                    speed = 11;
                // 按下alt减速
                }else if(event.altKey){
                    speed = 5;
                // 如果按下其他键则保持原来的速度
                }else{
                    speed = 8;
                }

                kc = event.keyCode;
            }

            // 用定时器来单独控制移动方向(从而使物体运动时不会卡顿)
            setInterval(function(){
                // 上：38，下：40，左：37，右：39
                if(kc == 38){
                    box.style.top = (box.offsetTop-speed)+"px";  
                }
                if(kc == 40){
                    box.style.top = (box.offsetTop+speed)+"px";  
                }
                if(kc == 37){
                    box.style.left = (box.offsetLeft-speed)+"px";  
                }
                if(kc == 39){
                    box.style.left = (box.offsetLeft+speed)+"px";  
                }
            },20);

            // 绑定按键松开的响应事件
            document.onkeyup = function(){
                // 设置移动方向为0
                kc = 0;
            }
        }
    </script>
    <style>
        .box{
            position: absolute;
            width: 20px;
            height: 20px;
            background-color: orange;
        }
    </style>
</head>
<body>
    <div class="box"></div>
</body>
</html>